package ru.spb.osll.myfit.client.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.service.SuiteService;
import ru.spb.osll.myfit.client.service.SuiteServiceAsync;
import ru.spb.osll.myfit.client.view.ViewConstants;
import ru.spb.osll.myfit.common.TextParsingTools;
import ru.spb.osll.myfit.common.util.Pair;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SuitesWidget extends Composite {
  private final Tree m_widget = new Tree();
  private final SuiteServiceAsync m_suiteService = GWT.create(SuiteService.class);
  private final ErrorDialog m_errorDialog = new ErrorDialog();

  private final Map<TreeItem, Pair<String, Boolean>> item2info = new HashMap<TreeItem, Pair<String, Boolean>>();

  public SuitesWidget() {
    m_widget.setStyleName(IStyleConstants.SUITES_LIST_PANEL_STYLE);
    initWidget(m_widget);

    m_widget.addOpenHandler(new OpenHandler<TreeItem>() {
      @Override
      public void onOpen(OpenEvent<TreeItem> treeItemOpenEvent) {
        TreeItem item = treeItemOpenEvent.getTarget();
        Pair<String, Boolean> itemInfo = item2info.get(item);
        if (itemInfo.getSecond()) {
          String path = itemInfo.getFirst();
          loadAndAddSuites(item, path == null ? "" : path);
        }
      }
    });

    loadAndAddSuites(m_widget, "");
  }

  private void loadAndAddSuites(final HasTreeItems container, final String path) {
    m_suiteService.getSuites(path, new AsyncCallback<List<Pair<String, Boolean>>>() {
      @Override
      public void onFailure(Throwable throwable) {
        m_errorDialog.setMessage(throwable);
        m_errorDialog.center();
      }

      @Override
      public void onSuccess(List<Pair<String, Boolean>> suites) {
        container.removeItems();
        String prefix = path == null || path.isEmpty() ? "" : path + TextParsingTools.ADDRESS_BAR_SEPARATOR;
        for (final Pair<String, Boolean> suite : suites) {
          final String suitePath = prefix + suite;
          TreeItem item = new TreeItem(new Anchor(suite.getFirst(), ViewConstants.SUITE_ADDRESS + "?id=" + suitePath));
          if (suite.getSecond())
            item.addTextItem("Loading...");
          container.addItem(item);
          item2info.put(item, suite);
        }
      }
    });
  }
}
